import fetch from 'node-fetch'
import ws from 'ws'
global.fetch = fetch
global.WebSocket = ws

import { createDfuseClient } from '@dfuse/client'
// DFUSE_API_KEY=server_900401d17e66c2c708639a26ede9a48f node index.eosio.js

const client = createDfuseClient({
  apiKey: 'b3ff420c4e3a353a55a77efe3efefc9b',
  network: 'wax.dfuse.eosnation.io',
  // network: 'eos.dfuse.eosnation.io'
})

// // You must use a `$cursor` variable so stream starts back at last marked cursor on reconnect!
const operation = `subscription($cursor: String!) {
  searchTransactionsForward(query:"receiver:farmerstoken action:transfers", cursor: $cursor) {
    undo cursor
    trace { id matchingActions { json } }
  }
}`
// account:farmerstoken action:transfers
// receiver:farmerstoken action:transfers
// farmerstoken - transfers

async function main() {
  const stream = await client.graphql(operation, (message) => {
    if (message.type === 'data') {
      const {
        undo,
        cursor,
        trace: { id, matchingActions },
      } = message.data.searchTransactionsForward
      matchingActions.forEach(({ json: { from, to, quantities, memo } }) => {
        if (memo === 'withdraw' || memo === 'deposit') {
          console.log(`${id} ${from} -> ${to} ${memo} [${quantities}]${undo ? ' REVERTED' : ''}`)
        }
        // console.log(json);
      })

      // Mark stream at cursor location, on re-connect, we will start back at cursor
      stream.mark({ cursor })
    }

    if (message.type === 'error') {
      console.log('An error occurred', message.errors, message.terminal)
    }

    if (message.type === 'complete') {
      console.log('Completed')
    }
  })

  // Waits until the stream completes, or forever
  await stream.join()
  await client.release()
}

main().catch((error) => console.log('Unexpected error', error))

// 获取验证token ，用于REST接口
// https://docs.dfuse.eosnation.io/platform/dfuse-cloud/authentication/

// fetch('https://eos.dfuse.eosnation.io/v0/block_id/by_time?time=2019-03-04T10:36:14.5Z&comparator=gte', {
//   headers: {
//     'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiaHR0cHM6Ly9kZnVzZS5lb3NuYXRpb24uaW8vIl0sImV4cCI6MTY0MjA5ODEzMiwiaWF0IjoxNjQyMDExNzMyLCJpc3MiOiJodHRwczovL2FwaS5kZnVzZS5lb3NuYXRpb24uaW8vdjEvIiwic3ViIjoidWlkOjU1MTE0MTEuZW9zbiIsImFwaV9rZXlfaWQiOiIxNjQyMDEwMDk3OTkwIiwicXVvdGEiOjEyMCwicmF0ZSI6MTAsIm5ldHdvcmtzIjpbeyJuYW1lIjoiZW9zIiwicXVvdGEiOjEyMCwicmF0ZSI6MTB9LHsibmFtZSI6IndheCIsInF1b3RhIjoxMjAsInJhdGUiOjEwfSx7Im5hbWUiOiJreWxpbiIsInF1b3RhIjoxMjAsInJhdGUiOjEwfSx7Im5hbWUiOiJqdW5nbGUiLCJxdW90YSI6MTIwLCJyYXRlIjoxMH0seyJuYW1lIjoid2F4dGVzdCIsInF1b3RhIjoxMjAsInJhdGUiOjEwfSx7Im5hbWUiOiJvcmUiLCJxdW90YSI6MTIwLCJyYXRlIjoxMH0seyJuYW1lIjoib3Jlc3RhZ2UiLCJxdW90YSI6MTIwLCJyYXRlIjoxMH0seyJuYW1lIjoidGVzdG5ldCIsInF1b3RhIjoxMjAsInJhdGUiOjEwfV19.QDrU8BumHCpx8M7K7a9LVJgbJrhH08LGHWk9XptKtCQ'
//   }
// }).then(console.log)
